var util = require('md5.js');



var isProd = true;
var imageDomain = isProd ? "https://zy-api.hui520.com" : "http://localhost"

// toast
function toast(title, icon, duration, cb) {
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration,
    success: function() {
      setTimeout(() => {
        wx.hideToast()
        if (cb) {
          cb()
        }
      }, duration)
    }
  })
  
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function getCurDate() {
  var date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()


  return [year, month, day].map(formatNumber).join('-')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function signPara(appKey, privateKey, method, curTimeStamp) {
    var sign = 'appKey' + appKey + 'method' + method + 'timestamp' + curTimeStamp + privateKey
  return util.hex_md5(sign)
}

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + hours + seperator2 + minutes
            + seperator2 + seconds;
    return currentdate;
}

//校验链接
const matchUrl = (source) => {
  if (source === null || source === undefined) {
    return false;
  }
  let result = source.match('^(https://)|(http://)');
  if (!result) {
    return false;
  }
  return true;
}

const uploadImage = (count, theSuccess, theFail) => {
  wx.chooseImage({
    count: count,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (files) {
      theSuccess && theSuccess(files.tempFilePaths)
    },
    fail: function (error) {
      console.error(error)
      let errorMessage = '';
      if (error.errMsg !== 'chooseImage:fail cancel') {
        errorMessage = '图片选择失败'
      }
      theFail && theFail(errorMessage)
    }
  })
}

// 上传视频
const uploadVideo = (theSuccess, theFail) => {
  wx.chooseVideo({
    sizeType: ['compressed'],
    sourceType: ['album'],
    maxDuration: 60,
    success: function (file) {
      if (file.duration > 180) {
        theFail && theFail('请上传3分钟以内的视频');
        return
      }
      theSuccess && theSuccess(file.tempFilePath, file.thumbTempFilePath);
    },
    fail: function (error) {
      console.error(error)
      let errorMessage = '';
      if (error.errMsg !== 'chooseVideo:fail cancel') {
        errorMessage = '视频选择失败'
      }
      theFail && theFail(errorMessage)
    }
  })
}

const calTimeMillAfterDayOfBegin = (time) => {
  var beginTime = new Date('1970/01/01 00:00:00');
  var endTime = new Date('1970/01/01 ' + time + ':00');

  return endTime.getTime() - beginTime.getTime();
}

const calNowTimeMillAfterDayOfBegin = () => {
    var beginTime = new Date(new Date().toLocaleDateString()).getTime();
    var endTime = new Date().getTime();

    console.log((endTime - beginTime) + " ms");

    return endTime - beginTime;
}

const parseHourAndMinute = (millsecondsAfterDayOfBegin) => {
  var beginTime = new Date('1970/01/01 00:00:00');

  var timestamp = beginTime.getTime() + parseInt(millsecondsAfterDayOfBegin);

  var date = new Date(timestamp);

  var hh = date.getHours(); 
  if (hh < 10) {
    hh = '0' + hh;
  }
  var mm = date.getMinutes();
  if (mm < 10) {
    mm = '0' + mm;
  }
  return hh + ":" + mm;
}

const createDropdownitemOptions = (datas, textColumn, valueClumn, defaultText)  => {
  let options = [];
  let defaultOption = {'text': defaultText, 'value': ''};
  options.push(defaultOption);
  if (datas) {
    datas.forEach(item => {
      let option = {};
      option['text'] = item[textColumn];
      option['value'] = item[valueClumn];
      options.push(option);
    })
  }

  return options;
}

function getUrlParams(url) {
  var params = new Object();
  if (url.indexOf("?") != -1) {
      var str = url.substr(url.indexOf("?") + 1);
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
      }
  }
  return params;
}

function getDay(day){
  var today = new Date();
  var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
  today.setTime(targetday_milliseconds);
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear+"-"+tMonth+"-"+tDate;
}

function doHandleMonth(month){
    var m = month;
    if(month.toString().length == 1){
     m = "0" + month;
    }
    return m;
}

function getDateRange(type) {
  var days = 0;
  // 近一周
  if (type == '1') {
    days = 7;
  } 
  // 近1个月
  else if (type == '2') {
    days = 30;
  }
  // 近3个月
  else if (type == '3') {
    days = 90;
  }
  // 近半年
  else if (type == '4') {
    days = 183;
  }
  // 近1年
  else if (type == '5') {
    days = 365;
  }

  var beginDate = getDay(-days);
  var endDate = getDay(0);

  var dateRange = [beginDate, endDate];
  return dateRange;
}

function deepClone(source) {
    if (!source && typeof source !== 'object') {
      throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    })
    return targetObj
}

function getImageUrl(image, type) {
    if (!image || image == '') {
        return "/resource/images/common/none.jpg"
    } else if (image.indexOf('http') == 0) {
        return image
    } else {
        return imageDomain + "/uploadFile/" + image;
    }
}

module.exports = {
  toast: toast,
  formatTime: formatTime,
  signPara:signPara,
  getNowFormatDate:getNowFormatDate,
  matchUrl: matchUrl,
  uploadImage: uploadImage,
  uploadVideo: uploadVideo,
  calTimeMillAfterDayOfBegin: calTimeMillAfterDayOfBegin,
  calNowTimeMillAfterDayOfBegin: calNowTimeMillAfterDayOfBegin,
  parseHourAndMinute: parseHourAndMinute,
  createDropdownitemOptions: createDropdownitemOptions,
  getUrlParams: getUrlParams,
  getDay: getDay,
  getDateRange: getDateRange,
  getCurDate: getCurDate,
  deepClone: deepClone,
  getImageUrl: getImageUrl
}
